<template>
  <div class="common-layout" style="height: 100%;">
    <el-container>
      <el-header style="text-align: center;">
        <div class="editor-button-bar">
          <el-button title="加粗" @click="editor!.chain().focus().toggleBold().run()" type="info" plain>B</el-button>
          <el-button title="斜体" @click="editor!.chain().focus().toggleItalic().run()" type="info" plain>I</el-button>
          <el-button title="删除线" @click="editor!.chain().focus().toggleStrike().run()" type="info" plain>
            <p style="text-decoration: line-through;">D</p>
          </el-button>
          <el-button title="引用块" type="info" @click="editor!.chain().focus().toggleBlockquote().run()"
            plain>"</el-button>
          <el-dropdown>
            <el-button title="标题" type="info" plain>H1</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  @click="editor!.chain().focus().toggleHeading({ level: 1 }).run()">标题1</el-dropdown-item>
                <el-dropdown-item
                  @click="editor!.chain().focus().toggleHeading({ level: 2 }).run()">标题2</el-dropdown-item>
                <el-dropdown-item
                  @click="editor!.chain().focus().toggleHeading({ level: 3 }).run()">标题3</el-dropdown-item>
                <el-dropdown-item
                  @click=" editor!?.chain().focus().toggleHeading({ level: 4 }).toggleHeading({ level: 4 }).run();"
                  divided>正文</el-dropdown-item>
                <el-dropdown-item @click="clearParagraphStyles()">删除样式</el-dropdown-item>
                <el-dropdown-item @click="insertEmptyParagraph()">插入空段落</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button title="分隔线" type="info" @click="editor!.chain().focus().setHorizontalRule().run()" plain
            icon="Minus"></el-button>

          <el-dropdown>
            <el-button title="代码" type="info" plain>C</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="editor!.chain().focus().toggleCode().run();">行内代码</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().setCodeBlock().run();">代码块</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-dropdown>
            <el-button title="编号" type="info" plain icon="Tickets"></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="editor!.chain().focus().toggleBulletList().run()">项目列表</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().toggleOrderedList().run();">有序列表</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <button_link v-if="editor !== undefined" :editor="editor!"><!--插入超链接--></button_link>
          <el-dropdown>
            <el-button title="表格1" type="info" plain icon="Grid"></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  @click="editor!.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()">插入表格</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().deleteTable().run()">删除表</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().addColumnBefore().run()"
                  divided>插入列</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().addColumnAfter().run()">添加列</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().deleteColumn().run()">删除列</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().addRowBefore().run()" divided>插入行</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().addRowAfter().run()">添加行</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().deleteRow().run()">删除行</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().mergeOrSplit().run()" divided>合并|取消</el-dropdown-item>
                <el-dropdown-item @click="editor!.chain().focus().toggleHeaderCell().run()">切换标题</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <button_imgs v-if="editor !== undefined" :editor="editor"><!--图片插入--></button_imgs>
          <button_video ref="videoRef" v-if="editor !== undefined" :editor="editor"><!--视频插入--></button_video>
          <button_audio v-if="editor !== undefined" :editor="editor"><!--音频插入--></button_audio>
          <button_file ref="fileRef" v-if="editor !== undefined" :editor="editor"><!--附件插入--></button_file>
          <el-button v-if="false" disabled title="word导入" type="warning" plain icon="Notebook"></el-button>
          <button_download_web ref="webRef" v-if="editor !== undefined" :editor="editor"><!--下载插入网页--></button_download_web>
          <button_test v-if="false" :editor="editor!"></button_test>
        </div>
      </el-header>
      <el-main style="margin: 0px 4px;">
        <div class="farm-editor-box farm-content">
          <editor-content :editor="editor" />
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script setup lang="ts">
import button_download_web from "./editor_funcs/button_download_web.vue";
import button_audio from "./editor_funcs/button_audio.vue";
import button_video from "./editor_funcs/button_video.vue";
import button_imgs from "./editor_funcs/button_imgs.vue";
import button_test from "./editor_funcs/button_test.vue";
import { onMounted, onBeforeUnmount, ref } from "vue";
import button_link from "./editor_funcs/button_link.vue";
import { Editor, EditorContent } from "@tiptap/vue-3";
import StarterKit from "@tiptap/starter-kit";
import button_file from "./editor_funcs/button_file.vue";
import Color from "@tiptap/extension-color";
import TextStyle from "@tiptap/extension-text-style";
import ListItem from "@tiptap/extension-list-item";
import Link from '@tiptap/extension-link';
import Table from '@tiptap/extension-table';
import TableCell from '@tiptap/extension-table-cell';
import TableHeader from '@tiptap/extension-table-header';
import TableRow from '@tiptap/extension-table-row';
import Video from './tiptap_extension/extension-video';
import Audio from './tiptap_extension/extension-audio';
import File from './tiptap_extension/extension-file';
import LCard from './tiptap_extension/extension-linkcard';
import Image from '@tiptap/extension-image';

const editor = ref<Editor>();
const videoRef = ref();
const fileRef = ref();
const webRef =ref();
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
function clearParagraphStyles() {
  editor.value!.chain().focus()
    .clearNodes()  // 清除所有节点样式
    .unsetAllMarks()  // 移除所有文本标记
    .run();
}
function insertEmptyParagraph() {
  editor.value?.chain().focus().insertContentAt(0, "<p></p>").run();
}
/**
 * 获得编辑器的html
 */
const getHtml = () => {
  return editor.value!.getHTML();
}
/**
 *滚动到指定h1或h2或h3
 */
const scrollIntoVDom = (index: number) => {
  // 获取 class 为 'farm-content' 的元素
  const farmContent = document.querySelector('.farm-content');
  if (!farmContent) {
    console.error('未找到 class 为 "farm-content" 的元素');
    return;
  }
  // 使用 querySelectorAll 获取所有的 h1, h2, h3 标签，并按文档顺序排列
  const tags = farmContent.querySelectorAll('h1, h2, h3');
  if (index > 0 && index <= tags.length) {
    const targetHeading = tags[index - 1];
    if (targetHeading) {
      targetHeading.scrollIntoView({ behavior: 'smooth' });
    }
  } else {
    alert('无效的标题序号');
  }
};
const callButton = (button: string) => {
  if (button == 'video') {
    videoRef.value.call();
    return;
  }
  if (button == 'file') {
    fileRef.value.call();
    return;
  }
  if (button == 'web') {
    webRef.value.call();
    return;
  }
  console.error('没有button：' + button);
}
const setHtml = (html: string) => {
  editor.value?.chain().focus().setContent(html, false).run();
}
const insertHtml = (html: string) => {
  editor.value?.chain().focus().insertContent(html).run();
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

// 暴露方法给父组件
defineExpose({
  getHtml, scrollIntoVDom, callButton, setHtml,insertHtml
});
onMounted(() => {
  editor.value = new Editor({
    extensions: [
      Color.configure({ types: [TextStyle.name, ListItem.name] }),
      TextStyle,
      Video,
      Audio,
      StarterKit,
      File,
      LCard,
      Image,
      Link.configure({
        openOnClick: false,
      }),
      Table.configure({
        resizable: true,
      }),
      TableRow,
      TableHeader,
      TableCell,
    ], injectCSS: false,
    content: ``,
    editorProps: {
      // handlePaste(view, event) {
      //   // 获取粘贴的纯文本内容
      //   //const text = event.clipboardData?.getData('text/plain') || '';
      //   const text = event.clipboardData?.getData('text/html') || '';
      //   // text = text.replace(/<[^>]*>/g, '');
      //   // 如果有纯文本内容，则插入到当前光标位置
      //   if (text) {
      //     editor.value!.chain().focus().insertContent((text)).run();
      //   }
      //   // 阻止默认行为（即粘贴 HTML）
      //   return true;
      // }
    }
  });
});

onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.destroy();
  }
});




</script>
<style scoped>
/* 样式可以根据需要添加 */
.editor-button-bar {
  text-align: left;
  background-color: #f4f4f5;
  padding: 4px;
}

.editor-button-bar .el-button {
  width: 32px;
  height: 32px;
  margin: 1px;
  border-color: #f4f4f5;
}

.editor-button-bar .el-dropdown {
  border: 0px solid #f4f4f5;
}

.farm-editor-box {
  border-bottom: 1px dashed #dddddd;
  /* 将边框样式改为虚线 */
  margin-left: 20px;
  margin-right: 20px;
}

.ProseMirror:focus {
  font-size: 14px;
}

/* 移除 Tiptap 编辑器获得焦点时的蓝色边框 */
:deep(.ProseMirror:focus) {
  outline: none;
  border: none;
  box-shadow: none;
}

:deep(.ProseMirror-selectednode video, img) {
  border: 2px solid #adf;

}

:deep(.ProseMirror-selectednode img) {
  border: 2px solid #adf;

}

.editor:deep(.ProseMirror) {
  table {
    border-collapse: collapse;
    table-layout: fixed;
    width: 100%;
    margin: 0;
    overflow: hidden;

    td,
    th {
      min-width: 1em;
      border: 2px solid #ced4da;
      padding: 3px 5px;
      vertical-align: top;
      box-sizing: border-box;
      position: relative;

      >* {
        margin-bottom: 0;
      }
    }

    th {
      font-weight: bold;
      text-align: left;
      background-color: #f1f3f5;
    }

    .selectedCell:after {
      z-index: 2;
      position: absolute;
      content: "";
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      background: rgba(200, 200, 255, 0.4);
      pointer-events: none;
    }

    .column-resize-handle {
      position: absolute;
      right: -2px;
      top: 0;
      bottom: -2px;
      width: 4px;
      background-color: #adf;
      pointer-events: none;
    }

    p {
      margin: 0;
    }
  }


}

.tableWrapper {
  padding: 1rem 0;
  overflow-x: auto;
}

.resize-cursor {
  cursor: ew-resize;
  cursor: col-resize;
}
</style>
